package com.qf.hello.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

public class MyBatisUtil {

    private static SqlSessionFactory factory;
    private static ThreadLocal<SqlSession> TL=new ThreadLocal<>();

    static {
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            factory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //打开会话的方法
    public static SqlSession openSession(){
        SqlSession session=TL.get();
        if (Objects.isNull(session)){
            session = factory.openSession();
            TL.set(session);
        }
        return session;
    }
    //关闭会话的方法
    public static void closeSession(){
        SqlSession session = openSession();
        if (Objects.nonNull(session)){
            session.close();
            TL.remove();
        }
    }
    //提交事务
    public static void commit(){
        SqlSession session = openSession();
        session.commit();
        closeSession();
    }

    //回滚事务
    public static void rollback(){
        SqlSession session = openSession();
        session.rollback();
        closeSession();
    }
    //获取接口的方法
    public static <T extends Object> T getMapper(Class<T> clazz){
        SqlSession session = openSession();
        return session.getMapper(clazz);
    }

}
